package com.shopping.controller;

import com.shopping.common.Result;
import com.shopping.service.OrderService;
import com.shopping.service.UserService;
import com.shopping.service.ProductService;
import com.shopping.service.MessageService;
import com.shopping.entity.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdminStatisticsController {

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Resource
    private ProductService productService;

    @Resource
    private MessageService messageService;

    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();

            // 获取订单统计
            Object orderStats = orderService.getOrderStatistics();
            if (orderStats instanceof Map) {
                statistics.putAll((Map<String, Object>) orderStats);
            }

            // 获取用户统计
            Object userStats = userService.getUserStatistics();
            if (userStats instanceof Map) {
                statistics.putAll((Map<String, Object>) userStats);
            }

            // 获取商品统计
            Object productStats = productService.getProductStatistics();
            if (productStats instanceof Map) {
                statistics.putAll((Map<String, Object>) productStats);
            }

            // 获取留言统计
            Object messageStats = messageService.getMessageStatistics();
            if (messageStats instanceof Map) {
                statistics.putAll((Map<String, Object>) messageStats);
            }

            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/messages/latest")
    public Result<List<Message>> getLatestMessages(@RequestParam(defaultValue = "5") Integer limit) {
        try {
            List<Message> messages = messageService.getLatestMessages(limit);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error("获取最新留言失败: " + e.getMessage());
        }
    }
}